package cn.t.repository.impl.order;

import cn.t.converter.order.ReconDetailConverter;
import cn.t.core.repoistory.RepositoryImpl;
import cn.t.model.order.ReconDetailDO;
import cn.t.persistence.entity.order.ReconDetailPO;
import cn.t.persistence.mapper.order.ReconDetailMapper;
import cn.t.repository.order.ReconDetailRepository;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对账单明细表(ReconDetail)数据仓库
 *
 * @author t
 * @since 2024-05-24 10:18:10
 */
@Slf4j
@Repository
@AllArgsConstructor
public class ReconDetailRepositoryImpl extends RepositoryImpl<ReconDetailMapper, ReconDetailPO, ReconDetailConverter, ReconDetailDO> implements ReconDetailRepository {


    @Override
    public List<ReconDetailDO> findByModel(ReconDetailDO reconDetailDO, int start, Integer pageSize, String field, String direction) {

        String lastSql = StringUtils.hasText(field) ?
                " order by " + field + " " + direction + " limit " + start + "," + pageSize : " limit " + start + "," + pageSize;

        List<ReconDetailPO> list = getWrapper(reconDetailDO).last(lastSql).list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        return list.stream().map(converter::po2Model).collect(Collectors.toList());
    }

    private LambdaQueryChainWrapper<ReconDetailPO> getWrapper(ReconDetailDO reconDetailDO) {
        LambdaQueryChainWrapper<ReconDetailPO> wrapper = lambdaQuery();
        if (!ObjectUtils.isEmpty(reconDetailDO.getReconSn())) {
            wrapper.eq(ReconDetailPO::getReconSn, reconDetailDO.getReconSn());
        }
        if (!ObjectUtils.isEmpty(reconDetailDO.getOrderSn())) {
            wrapper.eq(ReconDetailPO::getOrderSn, reconDetailDO.getOrderSn());
        }
        if (!ObjectUtils.isEmpty(reconDetailDO.getWorkOrderSn())) {
            wrapper.eq(ReconDetailPO::getWorkOrderSn, reconDetailDO.getWorkOrderSn());
        }
        if (!ObjectUtils.isEmpty(reconDetailDO.getUserName())) {
            wrapper.eq(ReconDetailPO::getUserName, reconDetailDO.getUserName());
        }

        return wrapper;
    }

    @Override
    public long count(ReconDetailDO reconDetailDO) {
        return getWrapper(reconDetailDO).count();
    }

    @Override
    public void addBatch(List<ReconDetailDO> reconDetailDOS) {
        this.saveOrUpdateBatch( reconDetailDOS.stream().map(converter::model2Po).collect(Collectors.toList()));
    }
}
